package com.starinside.wp.repository.impl;

import com.starinside.wp.foundation.dto.StaffDTO;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import com.starinside.wp.foundation.vo.StaffVO;
import com.starinside.wp.repository.BabyNativeRepository;
import com.starinside.wp.repository.BaseNativeSqlRepository;
import com.starinside.wp.repository.StaffNativeRepository;
import com.starinside.wp.utils.DateUtil;
import com.starinside.wp.utils.ModelUtil;
import com.starinside.wp.utils.RemoteCallUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.text.ParseException;
import java.util.*;

@Repository
public class StaffRepositoryImpl extends BaseNativeSqlRepository implements StaffNativeRepository {

    @Value("${sso.server.url}")
    private String ssoServerUrl;

    public List<StaffVO> getStaffDTOList(List<String> ids) {
        return RemoteCallUtil.callOfList(ssoServerUrl + "/api/sso/other_system/ids_by_staff_list",
                ModelUtil.mapOf("staffIds", ids), null, StaffVO.class, "调用sso推送消息出错");
    }

    @Override
    public List<StaffVO> getStaffInClassRelByChildId(String childId) {

        List results = new ArrayList<>();

        //找到班主任
        {
            String sql = "select c.`inChargeTeacherId` as staffId " +
                    " from rel_classes_children rcc " +
                    " left join `classes` c on rcc.`classesId` = c.`id` " +
                    " where rcc.`childrenId` = :1" +
                    " GROUP BY staffId ";
            sql = formatSql(sql, Arrays.asList(childId));
            List items = sqlSingleList(sql);
            results.addAll(items);
        }

        //找到任课老师,保育,儿保医生
        String sqlTemp = "select rct.staffId as staffId" +
                " from rel_classes_children rcc " +
                " left join `%s` rct on rct.`classesId` = rcc.`classesId` " +
                " where rcc.`childrenId` = :1 " +
                " GROUP BY staffId ";

        String[] tables = new String[]{"rel_classes_teacher", "rel_classes_nurse", "rel_classes_doctor"};
        for (String tableName : tables){
            String sql = String.format(sqlTemp, tableName);
            sql = formatSql(sql, Arrays.asList(childId));
            List<Map> items = sqlSingleList(sql);
            results.addAll(items);
        }

        if (results.size() == 0){
            return new ArrayList<>();
        }


        List<StaffVO> items = getStaffDTOList(results);

        return items;
    }
}
